package com.xiaomitest;

import java.util.LinkedList;
import java.util.Queue;

public class TopuSort {

    public static void main(String[] args) {

    }

    public boolean canFinish(int numCourses, int[][] prerequisites) {
        // 邻接矩阵
        int[][] matrix = new int[numCourses][numCourses];
        // 图中结点的入度
        int[] inDegree = new int[numCourses];
        for (int i = 0; i < prerequisites.length; i++) {
            int pre = prerequisites[i][1];
            int cur = prerequisites[i][0];
            // ready入度加1
            if (matrix[pre][cur] == 0) {
                inDegree[cur]++;
            }
            // 有边置为1
            matrix[pre][cur] = 1;
        }
        int count = 0;
        // 拓扑排序 使得入度为0的结点入队列
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < inDegree.length; i++) {
            if (inDegree[i] == 0) {
                queue.offer(i);
            }
        }

        while (!queue.isEmpty()) {
            int course = queue.poll();
            count++;
            // 根据邻接矩阵找下一个入度为0的入队列
            for (int i = 0; i < numCourses; i++) {
                if (matrix[course][i] != 0) {
                    inDegree[i]--;
                    if (inDegree[i] == 0) {
                        queue.offer(i);
                    }
                }

            }
        }
        return count == numCourses;

    }

}
